package com.yunqing.restkeeper.web.common.response;

import com.yunqing.restkeeper.common.utils.Result;
import com.yunqing.restkeeper.web.common.response.vo.PageVO;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @ClassName ResponseAdvisor
 * @Description 返回结果统一转换
 * @author: puyunqing
 * @Date: 2025/6/16
 */
//声明该类为一个增强类，并且数据返回会以json形式返回
@RestControllerAdvice(basePackages = "com.yunqing")
public class ResponseAdvisor implements ResponseBodyAdvice<Object> {

    /**
     * 判断哪些需要拦截
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * 返回结果包装
     *
     * @param body                  controller返回的数据
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if (body instanceof Result) {
            return body;
        }

        if (body instanceof Boolean) {
            boolean result = (boolean) body;
            return new BaseResponse<Boolean>(result);
        }

        if (body instanceof PageVO) {
            return new BaseResponse<>(body);
        }

        return new BaseResponse<>(body);
    }
}
